@extends('layouts.app')

@section('title', '统计分析')

@section('main-content')
<div class="screen">
    <div class="app-container">
        <!-- 顶部标题区域：统计类型下拉 + 统计周期切换 -->
        <div class="header-controls">
            <div class="stats-type-dropdown">
                <button class="stats-type-btn" id="stats-type-btn">
                    <span class="stats-type-text">支出</span>
                    <span class="dropdown-arrow">▼</span>
                </button>
                <div class="stats-type-menu" id="stats-type-menu">
                    <div class="stats-type-option active" data-type="expense">支出</div>
                    <div class="stats-type-option" data-type="income">收入</div>
                    <div class="stats-type-option" data-type="all">全部</div>
                </div>
            </div>
            
            <div class="period-tabs">
                <button class="period-tab" data-period="week">周</button>
                <button class="period-tab active" data-period="month">月</button>
                <button class="period-tab" data-period="year">年</button>
            </div>
        </div>
        
        <!-- 时间选择切换 -->
        <div class="time-tabs" id="time-tabs">
            <button class="time-nav-btn" id="prev-period">‹</button>
            <div class="time-tabs-container" id="time-tabs-container">
                <!-- 动态生成时间选项 -->
            </div>
            <button class="time-nav-btn" id="next-period">›</button>
        </div>
        
        <!-- 时间显示和收支汇总 -->
        <div class="time-summary-section" style="position: relative;">
            <div class="current-period">
                <div class="period-display" id="period-display">{{ date('Y年n月') }} <span class="period-arrow">▼</span></div>
            </div>

            <!-- 时间选择器弹窗 -->
            <div class="time-picker" id="time-picker">
                <div class="time-picker-header">
                    <button class="time-nav-btn" id="prev-time">‹</button>
                    <span class="time-display" id="time-display">{{ date('Y年') }}</span>
                    <button class="time-nav-btn" id="next-time">›</button>
                </div>
                <div class="time-grid" id="time-grid">
                    <!-- 动态生成时间选项 -->
                </div>
            </div>
            
            <div class="summary-stats" id="summary-stats">
                <!-- 全部统计时显示：收入、支出、结余 -->
                <div class="summary-item all-stats" id="income-item">
                    <div class="summary-amount income" id="total-income">0</div>
                    <div class="summary-label">收入</div>
                </div>
                <div class="summary-item all-stats" id="expense-item">
                    <div class="summary-amount expense" id="total-expense">0</div>
                    <div class="summary-label">支出</div>
                </div>
                <div class="summary-item all-stats" id="balance-item">
                    <div class="summary-amount net" id="net-income">0</div>
                    <div class="summary-label">结余</div>
                </div>
                
                <!-- 单项统计时显示：总计、笔数、平均 -->
                <div class="summary-item single-stats" id="total-item" style="display: none;">
                    <div class="summary-amount" id="single-total">0</div>
                    <div class="summary-label">总计</div>
                </div>
                <div class="summary-item single-stats" id="count-item" style="display: none;">
                    <div class="summary-amount" id="single-count">0</div>
                    <div class="summary-label">笔数</div>
                </div>
                <div class="summary-item single-stats" id="average-item" style="display: none;">
                    <div class="summary-amount" id="single-average">0</div>
                    <div class="summary-label">平均</div>
                </div>
            </div>
        </div>

        <!-- 图表选项卡 -->
        <div class="chart-tabs" id="chart-tabs" style="display: none; margin-bottom: 0; padding-bottom: 0;">
            <button class="chart-tab active" data-chart="daily">日收支</button>
        </div>

        <!-- 图表容器 -->
        <div class="chart-container">
            <canvas id="trend-chart" height="180"></canvas>
        </div>

        <!-- 排行榜部分 -->
        <div class="ranking-section">
                <div class="ranking-header">
                    <div class="ranking-title">分类排行</div>
                    <div class="category-tabs">
                        <button class="category-tab active" data-level="1">一级分类</button>
                        <button class="category-tab" data-level="2">二级分类</button>
                    </div>
                </div>

                <!-- 饼图统计 -->
                <div class="chart-container">
                    <canvas id="pie-chart"></canvas>
                </div>

                <div class="ranking-list" id="ranking-list">
                <!-- 动态生成排行榜内容 -->
            </div>
        </div>

        <div style="height: 80px;"></div> <!-- 底部空间，防止内容被底部导航遮挡 -->
    </div>
</div>
@endsection

@push('styles')
    <style>
        /* 手机端紧凑设计 */
        /* 顶部标题区域样式 */
        .header-controls {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: white;
            padding: 12px 15px;
            border-bottom: 1px solid #e2e8f0;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }

        /* 统计类型下拉按钮样式 */
        .stats-type-dropdown {
            position: relative;
        }
        .stats-type-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 16px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
            min-width: 80px;
        }
        .stats-type-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
        }
        .dropdown-arrow {
            font-size: 12px;
            transition: transform 0.3s ease;
        }
        .stats-type-btn.active .dropdown-arrow {
            transform: rotate(180deg);
        }
        .stats-type-menu {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background: white;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
            z-index: 1000;
            margin-top: 8px;
            overflow: hidden;
            display: none;
        }
        .stats-type-option {
            padding: 12px 16px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 15px;
            font-weight: 500;
            color: #374151;
        }
        .stats-type-option:hover {
            background: #f8fafc;
        }
        .stats-type-option.active {
            background: #667eea;
            color: white;
        }

        /* 统计周期带框tab样式 */
        .period-tabs {
            display: flex;
            background: #f8fafc;
            border-radius: 12px;
            padding: 4px;
            border: 1px solid #e2e8f0;
        }
        .period-tab {
            padding: 8px 16px;
            border: none;
            background: transparent;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            color: #64748b;
            min-width: 50px;
        }
        .period-tab:hover {
            color: #667eea;
        }
        .period-tab.active {
            background: white;
            color: #667eea;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
            border: 1px solid #e2e8f0;
        }

        /* 时间选择切换样式 - 简洁无边框 */
        .time-tabs {
            background: white;
            padding: 12px 0;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            align-items: center;
            position: relative;
        }
        .time-tabs-container {
            display: flex;
            padding: 0 5px;
            gap: 4px;
            flex: 1;
            overflow-x: auto;
            overflow-y: hidden;
            -webkit-overflow-scrolling: touch;
            scrollbar-width: none; /* Firefox */
            -ms-overflow-style: none; /* IE and Edge */
            scroll-behavior: smooth;
            margin: 0 40px; /* 为左右按钮留出空间 */
            /* 增强的滑动支持 */
            touch-action: pan-x;
            overscroll-behavior-x: contain;
            scroll-snap-type: x proximity;
        }
        .time-tabs-container::-webkit-scrollbar {
            display: none; /* Chrome, Safari, Opera */
        }
        /* 滑动指示器 */
        .time-tabs {
            --show-left-indicator: 0;
            --show-right-indicator: 1;
        }
        .time-tabs::before,
        .time-tabs::after {
            content: '';
            position: absolute;
            top: 0;
            bottom: 0;
            width: 20px;
            pointer-events: none;
            z-index: 5;
            transition: opacity 0.3s ease;
        }
        .time-tabs::before {
            left: 40px;
            background: linear-gradient(to right, rgba(255,255,255,0.9), transparent);
            opacity: var(--show-left-indicator);
        }
        .time-tabs::after {
            right: 40px;
            background: linear-gradient(to left, rgba(255,255,255,0.9), transparent);
            opacity: var(--show-right-indicator);
        }
        .time-nav-btn {
            background: rgba(255, 255, 255, 0.95);
            border: 1px solid #e2e8f0;
            font-size: 18px;
            color: #667eea;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            flex-shrink: 0;
            transition: all 0.2s ease;
            border-radius: 50%;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            z-index: 10;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }
        .time-nav-btn:hover {
            background: #667eea;
            color: white;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        .time-nav-btn:active {
            transform: translateY(-50%) scale(0.95);
        }
        #prev-period {
            left: 10px;
        }
        #next-period {
            right: 10px;
        }
        .time-tab {
            padding: 8px 12px;
            border: none;
            background: transparent;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            color: #64748b;
            white-space: nowrap;
            flex-shrink: 0;
            position: relative;
            /* 滚动吸附 */
            scroll-snap-align: center;
            min-width: 60px;
            text-align: center;
        }
        .time-tab:hover {
            color: #667eea;
            background: rgba(102, 126, 234, 0.05);
        }
        .time-tab.active {
            color: #667eea;
            font-weight: 600;
            background: rgba(102, 126, 234, 0.1);
        }
        .time-tab.active::after {
            content: '';
            position: absolute;
            bottom: -12px;
            left: 50%;
            transform: translateX(-50%);
            width: 20px;
            height: 3px;
            background: #667eea;
            border-radius: 2px;
        }

        /* 时间选择器弹窗样式 */
        .period-display {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.2s ease;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }

        .period-display:hover {
            background: #f1f5f9;
        }

        .period-arrow {
            font-size: 12px;
            transition: transform 0.3s ease;
        }

        .period-display.active .period-arrow {
            transform: rotate(180deg);
        }

        .time-picker {
            position: absolute;
            top: 100%;
            left: 15px;
            right: 15px;
            background: white;
            border-radius: 16px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
            z-index: 9999;
            padding: 20px;
            margin-top: 10px;
            display: none;
        }

        .time-picker-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .time-display {
            font-size: 18px;
            font-weight: 600;
            color: #2d3748;
        }

        .time-grid {
            display: grid;
            gap: 12px;
        }

        .time-grid.week-grid {
            grid-template-columns: repeat(4, 1fr);
        }

        .time-grid.month-grid {
            grid-template-columns: repeat(3, 1fr);
        }

        .time-grid.year-grid {
            grid-template-columns: repeat(2, 1fr);
        }

        .time-item {
            padding: 12px;
            text-align: center;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-size: 14px;
            color: #4a5568;
            border: 1px solid #e2e8f0;
        }

        .time-item:hover {
            background: #f0f5ff;
            color: #667eea;
            border-color: #667eea;
        }

        .time-item.active {
            background: #667eea;
            color: white;
            border-color: #667eea;
        }
        .time-summary-section {
            margin: 0;
            background: white;
            padding: 15px;
            border-bottom: 1px solid #e2e8f0;
        }
        .current-period {
            text-align: center;
            margin-bottom: 12px;
        }
        .period-display {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.2s ease;
            display: inline-block;
        }
        .period-display:hover {
            background: #f1f5f9;
        }
        .summary-stats {
            display: flex;
            justify-content: space-around;
            gap: 10px;
        }
        .summary-item {
            text-align: center;
            flex: 1;
        }
        .summary-amount {
            font-size: 18px;
            font-weight: 700;
            margin-bottom: 2px;
            color: #1e293b;
        }
        .summary-amount.income {
            color: #10b981;
        }
        .summary-amount.expense {
            color: #ef4444;
        }
        .summary-amount.net {
            color: #667eea;
        }
        .summary-label {
            font-size: 11px;
            color: #64748b;
            font-weight: 500;
        }
        .chart-tabs {
            display: flex;
            background: white;
            border-radius: 16px;
            margin: 15px 15px 0 15px;
            padding: 6px;
            padding-bottom: 0;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }
        .chart-tab {
            flex: 1;
            padding: 12px 16px;
            text-align: center;
            background: transparent;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            border-radius: 12px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            color: #64748b;
            position: relative;
        }
        .chart-tab:hover {
            color: #334155;
            background: rgba(102, 126, 234, 0.05);
        }
        .chart-tab.active {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
            transform: translateY(-1px);
        }
        .ranking-section {
            background: white;
            padding: 10px;
            border-top: 1px solid #e2e8f0;
        }
        .ranking-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .ranking-title {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
        }
        .ranking-tabs {
            display: flex;
            margin-bottom: 12px;
            background: white;
            border-radius: 16px;
            padding: 6px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }
        .ranking-tab {
            flex: 1;
            padding: 14px 16px;
            text-align: center;
            background: transparent;
            border: none;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            color: #64748b;
            border-radius: 12px;
        }
        .ranking-tab:hover {
            color: #334155;
            background: rgba(239, 68, 68, 0.05);
        }
        .ranking-tab.active {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
            transform: translateY(-1px);
        }
        .ranking-tab:first-child {
            border-radius: 12px;
        }
        .ranking-tab:last-child {
            border-radius: 12px;
        }
        .category-tabs {
            display: flex;
            background: white;
            border-radius: 14px;
            padding: 4px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.06);
            border: 1px solid rgba(0,0,0,0.05);
        }
        .category-tab {
            padding: 10px 16px;
            text-align: center;
            background: transparent;
            border: none;
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
            border-radius: 10px;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            color: #64748b;
            white-space: nowrap;
        }
        .category-tab:hover {
            color: #334155;
            background: rgba(16, 185, 129, 0.05);
        }
        .category-tab.active {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
            box-shadow: 0 3px 10px rgba(16, 185, 129, 0.3);
            transform: translateY(-1px);
        }
        .ranking-list {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }
        .ranking-item {
            display: flex;
            align-items: center;
            padding: 18px 20px;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            transition: all 0.2s ease;
        }
        .ranking-item:hover {
            background: rgba(102, 126, 234, 0.02);
        }
        .ranking-item:last-child {
            border-bottom: none;
        }
        .ranking-rank {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            margin-right: 16px;
            font-size: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .ranking-rank.top1 {
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%);
            color: #92400e;
            box-shadow: 0 4px 12px rgba(255, 215, 0, 0.4);
        }
        .ranking-rank.top2 {
            background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%);
            color: #374151;
            box-shadow: 0 4px 12px rgba(209, 213, 219, 0.4);
        }
        .ranking-rank.top3 {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4);
        }
        .ranking-rank.other {
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            color: #64748b;
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
        }
        .ranking-info {
            flex: 1;
        }
        .ranking-name {
            font-weight: 600;
            margin-bottom: 4px;
            color: #1e293b;
            font-size: 15px;
        }
        .ranking-percent {
            font-size: 12px;
            color: #64748b;
            font-weight: 500;
        }
        .ranking-amount {
            font-weight: 700;
            color: #1e293b;
            font-size: 16px;
        }
        .chart-container {
            margin: 0;
            border-radius: 0;
            padding: 0;
            box-shadow: none;
            border: none;
            background: white;
        }
        
        /* 页面整体美化 */
        body {
            background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
        }
        
        .container-fluid {
            background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
            min-height: 100vh;
        }
        
        /* 时间显示和收支汇总样式 */
        .time-summary-section {
            margin: 0;
            background: white;
            padding: 15px;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .current-period {
            text-align: center;
            margin-bottom: 12px;
        }
        
        .period-display {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
            cursor: pointer;
            padding: 8px 12px;
            border-radius: 8px;
            transition: all 0.2s ease;
            display: inline-block;
        }
        
        .period-display:hover {
            background: #f1f5f9;
        }
        
        .summary-stats {
            display: flex;
            justify-content: space-around;
            gap: 10px;
        }
        
        .summary-item {
            text-align: center;
            flex: 1;
        }
        
        .summary-amount {
            font-size: 18px;
            font-weight: 700;
            margin-bottom: 2px;
            color: #1e293b;
        }
        
        /* 单项统计配色 - 与分类详情页保持一致 */
        #single-total {
            color: #ef4444 !important; /* 总计 - 红色 */
        }
        
        #single-count {
            color: #667eea !important; /* 笔数 - 蓝色 */
        }
        
        #single-average {
            color: #10b981 !important; /* 平均 - 绿色 */
        }
        
        .summary-label {
            font-size: 11px;
            color: #64748b;
            font-weight: 500;
        }
        
        .ranking-tabs {
            display: flex;
            margin-bottom: 12px;
            background: white;
            border-radius: 16px;
            padding: 6px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }
        
        .ranking-tab {
            flex: 1;
            padding: 14px 16px;
            text-align: center;
            background: transparent;
            border: none;
            cursor: pointer;
            font-size: 15px;
            font-weight: 600;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            color: #64748b;
            border-radius: 12px;
        }
        
        .ranking-tab:hover {
            color: #334155;
            background: rgba(239, 68, 68, 0.05);
        }
        
        .ranking-tab.active {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
            color: white;
            box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
            transform: translateY(-1px);
        }
        
        .category-tabs {
            display: flex;
            margin-bottom: 12px;
            background: white;
            border-radius: 14px;
            padding: 4px;
            box-shadow: 0 2px 12px rgba(0,0,0,0.06);
            border: 1px solid rgba(0,0,0,0.05);
        }
        
        .category-tab {
            flex: 1;
            padding: 10px 12px;
            text-align: center;
            background: transparent;
            border: none;
            cursor: pointer;
            font-size: 13px;
            font-weight: 600;
            border-radius: 10px;
            transition: all 0.2s ease;
            color: #64748b;
        }
        
        .category-tab:hover {
            color: #667eea;
            background: rgba(102, 126, 234, 0.05);
        }
        
        .category-tab.active {
            background: #667eea;
            color: white;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3);
        }

        /* 添加页面整体美化 */
        .app-container {
            background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
        }

        .header {
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid rgba(0,0,0,0.05);
            box-shadow: 0 2px 20px rgba(0,0,0,0.05);
        }

        .greeting {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .category-controls,
        .comparison-controls {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .form-select,
        .form-input {
            padding: 8px 12px;
            border: 1px solid #d1d5db;
            border-radius: 6px;
            font-size: 14px;
            background: white;
        }

        .form-select:focus,
        .form-input:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }

        .category-stats {
            display: grid;
            grid-template-columns: 1fr 300px;
            gap: 20px;
            align-items: start;
        }

        @media (max-width: 768px) {
            .category-stats {
                grid-template-columns: 1fr;
            }

            .section-header {
                flex-direction: column;
                align-items: stretch;
            }

            .chart-tabs {
                justify-content: center;
            }
        }

        .category-chart {
            position: relative;
            height: 300px;
        }

        .category-list {
            max-height: 300px;
            overflow-y: auto;
        }

        .category-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 12px 0;
            border-bottom: 1px solid #f1f5f9;
        }

        .category-item:last-child {
            border-bottom: none;
        }

        .category-name {
            font-weight: 500;
            color: #1e293b;
        }

        .category-amount {
            font-weight: 600;
            color: #3b82f6;
        }

        .category-percentage {
            font-size: 12px;
            color: #64748b;
        }

        .comparison-chart {
            position: relative;
            height: 300px;
        }

        .header-actions {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 200px;
            color: #64748b;
        }
    </style>
@endpush

@push('scripts')
    <script src="{{ asset('/js/chart.js') }}"></script>
    <script>
        $(document).ready(function() {
            let trendChart = null;
            let pieChart = null;
            let categoryChart = null;
            let comparisonChart = null;
            let currentTrendType = 'daily';

            // 全局变量
            let currentPeriod = 'month';
            let currentChart = 'daily';
            let currentRankingType = 'expense';
            let currentCategoryLevel = 1;
            let currentStatsType = 'expense'; // 当前统计类型：expense, income, all

            // URL参数管理函数
            function getUrlParams() {
                const params = new URLSearchParams(window.location.search);
                return {
                    period: params.get('period') || 'month',
                    stats_type: params.get('stats_type') || 'expense',
                    year: params.get('year') ? parseInt(params.get('year')) : new Date().getFullYear(),
                    month: params.get('month') ? parseInt(params.get('month')) : new Date().getMonth() + 1,
                    week: params.get('week') ? parseInt(params.get('week')) : getCurrentWeekInMonth(new Date()),
                    category_level: params.get('category_level') ? parseInt(params.get('category_level')) : 1
                };
            }

            function updateUrlParams() {
                const params = new URLSearchParams();
                params.set('period', currentPeriod);
                params.set('stats_type', currentStatsType);
                params.set('year', currentYear);
                
                if (currentPeriod === 'month' || currentPeriod === 'week') {
                    params.set('month', currentMonth);
                }
                
                if (currentPeriod === 'week') {
                    params.set('week', currentWeek);
                }
                
                params.set('category_level', currentCategoryLevel);
                
                const newUrl = window.location.pathname + '?' + params.toString();
                window.history.replaceState({}, '', newUrl);
            }

            // 从URL参数初始化状态
            function initFromUrlParams() {
                const urlParams = getUrlParams();
                
                currentPeriod = urlParams.period;
                currentStatsType = urlParams.stats_type;
                currentYear = urlParams.year;
                currentMonth = urlParams.month;
                currentWeek = urlParams.week;
                currentCategoryLevel = urlParams.category_level;
                
                // 更新UI状态
                $('.period-tab').removeClass('active');
                $(`.period-tab[data-period="${currentPeriod}"]`).addClass('active');
                
                $('.stats-type-option').removeClass('active');
                $(`.stats-type-option[data-type="${currentStatsType}"]`).addClass('active');
                $('.stats-type-btn span:first').text($(`.stats-type-option[data-type="${currentStatsType}"]`).text());
                
                $('.category-tab').removeClass('active');
                $(`.category-tab[data-level="${currentCategoryLevel}"]`).addClass('active');
                
                // 根据统计类型显示/隐藏排行榜
                if (currentStatsType === 'all') {
                    $('.ranking-section').hide();
                } else {
                    $('.ranking-section').show();
                    currentRankingType = currentStatsType;
                }
            }

            // 计算指定日期在当月是第几周（基于周一到周日）
            function getCurrentWeekInMonth(date) {
                const year = date.getFullYear();
                const month = date.getMonth() + 1;
                const firstDay = new Date(year, month - 1, 1);
                
                // 找到当月第一个周一
                const firstMonday = new Date(firstDay);
                const dayOfWeek = firstDay.getDay(); // 0=周日, 1=周一, ..., 6=周六
                const daysToMonday = dayOfWeek === 0 ? 1 : (8 - dayOfWeek); // 如果是周日，需要1天到周一；其他情况计算到下一个周一的天数
                if (dayOfWeek !== 1) { // 如果第一天不是周一
                    firstMonday.setDate(firstDay.getDate() + daysToMonday);
                }
                
                // 如果传入的日期在第一个周一之前，返回0（表示属于上个月的周）
                if (date < firstMonday) {
                    return 0;
                }
                
                // 计算当前日期是第几周
                const diffTime = date.getTime() - firstMonday.getTime();
                const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));
                return Math.floor(diffDays / 7) + 1;
            }

            // 当前选中的时间
            let currentYear = new Date().getFullYear();
            let currentMonth = new Date().getMonth() + 1;
            let currentWeek = getCurrentWeekInMonth(new Date());

            // 初始化页面
            initFromUrlParams(); // 先从URL参数恢复状态
            
            // 根据当前统计类型初始化显示
            if (currentStatsType === 'all') {
                showAllStats();
            } else {
                showSingleStats();
            }
            
            loadSummaryData();
            loadTrendChart();
            loadRankingData();
            updateChartTabs();
            updateTimeTabs();
            updatePeriodDisplay();
            updateUrlParams(); // 确保URL参数是最新的

            // 统计类型下拉菜单交互
            $('.stats-type-btn').click(function(e) {
                e.stopPropagation();
                $(this).toggleClass('active');
                $('.stats-type-menu').toggle();
            });
            
            $('.stats-type-option').click(function() {
                const selectedType = $(this).text();
                const selectedDataType = $(this).data('type');
                $('.stats-type-btn span:first').text(selectedType);
                $('.stats-type-option').removeClass('active');
                $(this).addClass('active');
                $('.stats-type-menu').hide();
                $('.stats-type-btn').removeClass('active');
                
                // 更新当前统计类型
                currentStatsType = selectedDataType;
                
                // 根据统计类型显示/隐藏排行榜
                if (currentStatsType === 'all') {
                    $('.ranking-section').hide();
                } else {
                    $('.ranking-section').show();
                    // 同步排行榜类型
                    currentRankingType = currentStatsType;
                }
                
                // 更新URL参数
                updateUrlParams();
                
                // 重新加载数据
                loadSummaryData();
                loadTrendChart();
                if (currentStatsType !== 'all') {
                    loadRankingData();
                }
            });
            
            // 点击其他地方关闭下拉菜单
            $(document).click(function() {
                $('.stats-type-menu').hide();
                $('.stats-type-btn').removeClass('active');
            });
            
            // 时间周期切换
            $('.period-tab').click(function() {
                $('.period-tab').removeClass('active');
                $(this).addClass('active');
                currentPeriod = $(this).data('period');
                updateChartTabs();
                updatePeriodDisplay();
                updateTimeTabs();
                
                // 更新URL参数
                updateUrlParams();
                
                loadSummaryData();
                loadTrendChart();
                loadRankingData();
            });
            
            // 时间选择切换
            $(document).on('click', '.time-tab', function() {
                $('.time-tab').removeClass('active');
                $(this).addClass('active');
                
                const selectedDate = $(this).data('date');
                if (currentPeriod === 'week') {
                    currentWeek = selectedDate;
                } else if (currentPeriod === 'month') {
                    currentMonth = selectedDate;
                } else if (currentPeriod === 'year') {
                    currentYear = selectedDate;
                }
                
                updatePeriodDisplay();
                
                // 更新URL参数
                updateUrlParams();
                
                loadSummaryData();
                loadTrendChart();
                loadRankingData();
            });

            // 时间选择器交互
            // $('#period-display').click(function() {
            //     const picker = $('#time-picker');
            //     const isVisible = picker.is(':visible');

            //     if (isVisible) {
            //         picker.hide();
            //         $(this).removeClass('active');
            //     } else {
            //         generateTimeGrid();
            //         picker.show();
            //         $(this).addClass('active');
            //     }
            // });

            // 点击其他地方关闭时间选择器
            $(document).click(function(e) {
                if (!$(e.target).closest('.time-summary-section').length) {
                    $('#time-picker').hide();
                    $('#period-display').removeClass('active');
                }
            });

            // 时间导航
            $('#prev-time').click(function() {
                navigateTime(-1);
            });

            $('#next-time').click(function() {
                navigateTime(1);
            });
            
            // 时间选择器导航按钮事件
            $('#prev-period').click(function() {
                navigatePeriod(-1);
            });
            
            $('#next-period').click(function() {
                navigatePeriod(1);
            });

            // 图表标签切换
            $(document).on('click', '.chart-tab', function() {
                $('.chart-tab').removeClass('active');
                $(this).addClass('active');
                currentChart = $(this).data('chart');
                loadTrendChart();
            });

            // 移除排行榜类型切换，因为现在跟随顶部统计类型

            // 分类级别切换
            $('.category-tab').click(function() {
                $('.category-tab').removeClass('active');
                $(this).addClass('active');
                currentCategoryLevel = $(this).data('level');
                
                // 更新URL参数
                updateUrlParams();
                
                loadRankingData();
            });

            // 滚动到选中的时间标签
            function scrollToActiveTab() {
                const container = document.getElementById('time-tabs-container');
                const activeTab = container.querySelector('.time-tab.active');
                
                if (activeTab && container) {
                    const tabLeft = activeTab.offsetLeft;
                    const tabWidth = activeTab.offsetWidth;
                    const containerWidth = container.clientWidth;
                    const scrollLeft = container.scrollLeft;
                    
                    // 如果标签在可视区域外，则滚动到合适位置
                    if (tabLeft < scrollLeft) {
                        // 标签在左侧不可见，滚动到标签位置
                        container.scrollLeft = tabLeft - 20;
                    } else if (tabLeft + tabWidth > scrollLeft + containerWidth) {
                        // 标签在右侧不可见，滚动到标签可见
                        container.scrollLeft = tabLeft + tabWidth - containerWidth + 20;
                    }
                }
            }
            
            // 更新时间选择标签
            function updateTimeTabs() {
                const tabsContainer = $('#time-tabs-container');
                let tabsHtml = '';
                const now = new Date();
                const currentRealYear = now.getFullYear();
                const currentRealMonth = now.getMonth() + 1;
                const currentRealWeek = getCurrentWeekInMonth(now);
                
                if (currentPeriod === 'week') {
                    // 周统计：显示当前月的几个周
                    const firstDay = new Date(currentYear, currentMonth - 1, 1);
                    const lastDay = new Date(currentYear, currentMonth, 0);
                    
                    // 找到当月第一个周一
                    const firstMonday = new Date(firstDay);
                    const dayOfWeek = firstDay.getDay(); // 0=周日, 1=周一, ..., 6=周六
                    const daysToMonday = dayOfWeek === 0 ? 1 : (8 - dayOfWeek); // 如果是周日，需要1天到周一；其他情况计算到下一个周一的天数
                    if (dayOfWeek !== 1) { // 如果第一天不是周一
                        firstMonday.setDate(firstDay.getDate() + daysToMonday);
                    }
                    
                    // 计算当月有多少个完整的周（从周一开始）
                    let weekCount = 0;
                    let currentWeekStart = new Date(firstMonday);
                    
                    while (currentWeekStart <= lastDay) {
                        weekCount++;
                        currentWeekStart.setDate(currentWeekStart.getDate() + 7);
                    }
                    
                    // 限制到当前周（如果是当前月份和当前年份）
                    let maxWeek = weekCount;
                    
                    // 如果是当前年份和当前月份，限制到当前周
                    if (currentYear === currentRealYear && currentMonth === currentRealMonth && currentRealWeek > 0) {
                        maxWeek = Math.min(weekCount, currentRealWeek);
                    }
                    
                    // 确保当前选中的周不超过最大周数
                    if (currentWeek > maxWeek) {
                        currentWeek = maxWeek;
                    }
                    
                    for (let week = 1; week <= maxWeek; week++) {
                        const isActive = week === currentWeek ? 'active' : '';
                        tabsHtml += `<button class="time-tab ${isActive}" data-date="${week}">第${week}周</button>`;
                    }
                } else if (currentPeriod === 'month') {
                    // 月统计：显示当前年的12个月
                    for (let month = 1; month <= 12; month++) {
                        const isActive = month === currentMonth ? 'active' : '';
                        tabsHtml += `<button class="time-tab ${isActive}" data-date="${month}">${month}月</button>`;
                    }
                } else if (currentPeriod === 'year') {
                    // 年统计：显示包含今年往前的5年
                    const startYear = currentYear - 4;
                    
                    for (let year = startYear; year <= currentYear; year++) {
                        const isActive = year === currentYear ? 'active' : '';
                        tabsHtml += `<button class="time-tab ${isActive}" data-date="${year}">${year}年</button>`;
                    }
                }
                
                tabsContainer.html(tabsHtml);
                
                // 滚动到选中的标签
                setTimeout(() => {
                    scrollToActiveTab();
                }, 100);
            }
            
            // 更新图表标签
            function updateChartTabs() {
                const tabsContainer = $('#chart-tabs');
                let tabsHtml = '';

                if (currentPeriod === 'week') {
                    tabsHtml = '<button class="chart-tab active" data-chart="weekly">日收支</button>';
                    currentChart = 'weekly';
                } else if (currentPeriod === 'month') {
                    tabsHtml = '<button class="chart-tab active" data-chart="monthly">日收支</button>';
                    currentChart = 'monthly';
                } else if (currentPeriod === 'year') {
                    tabsHtml = '<button class="chart-tab active" data-chart="yearly">月收支</button>';
                    currentChart = 'yearly';
                }

                tabsContainer.html(tabsHtml);
            }

            // 更新时间显示
            function updatePeriodDisplay() {
                let displayText = '';

                if (currentPeriod === 'week') {
                    displayText = `${currentYear}年${currentMonth}月第${currentWeek}周`;
                } else if (currentPeriod === 'month') {
                    displayText = `${currentYear}年${currentMonth}月`;
                } else if (currentPeriod === 'year') {
                    displayText = `${currentYear}年`;
                }

                $('#period-display').html(displayText);
            }

            // 生成时间选择网格
            function generateTimeGrid() {
                const grid = $('#time-grid');
                const timeDisplay = $('#time-display');
                let gridHtml = '';
                let gridClass = '';

                if (currentPeriod === 'week') {
                    gridClass = 'week-grid';
                    timeDisplay.text(`${currentYear}年${currentMonth}月`);

                    // 生成当月的周，基于周一到周日的逻辑
                    const firstDay = new Date(currentYear, currentMonth - 1, 1);
                    const lastDay = new Date(currentYear, currentMonth, 0);
                    
                    // 找到当月第一个周一
                    const firstMonday = new Date(firstDay);
                    const dayOfWeek = firstDay.getDay(); // 0=周日, 1=周一, ..., 6=周六
                    const daysToMonday = dayOfWeek === 0 ? 1 : (8 - dayOfWeek); // 如果是周日，需要1天到周一；其他情况计算到下一个周一的天数
                    if (dayOfWeek !== 1) { // 如果第一天不是周一
                        firstMonday.setDate(firstDay.getDate() + daysToMonday);
                    }
                    
                    // 计算当月有多少个完整的周（从周一开始）
                    let weekCount = 0;
                    let currentWeekStart = new Date(firstMonday);
                    
                    while (currentWeekStart <= lastDay) {
                        weekCount++;
                        currentWeekStart.setDate(currentWeekStart.getDate() + 7);
                    }
                    
                    // 限制到当前周（如果是当前月份和当前年份）
                    const now = new Date();
                    const currentRealYear = now.getFullYear();
                    const currentRealMonth = now.getMonth() + 1;
                    const currentRealWeekInMonth = getCurrentWeekInMonth(now);
                    let maxWeek = weekCount;
                    
                    // 如果是当前年份和当前月份，限制到当前周
                    if (currentYear === currentRealYear && currentMonth === currentRealMonth && currentRealWeekInMonth > 0) {
                        maxWeek = Math.min(weekCount, currentRealWeekInMonth);
                    }

                    for (let week = 1; week <= maxWeek; week++) {
                        const isActive = week === currentWeek ? 'active' : '';
                        gridHtml += `<div class="time-item ${isActive}" data-week="${week}">第${week}周</div>`;
                    }
                } else if (currentPeriod === 'month') {
                    gridClass = 'month-grid';
                    timeDisplay.text(`${currentYear}年`);

                    // 生成12个月
                    for (let month = 1; month <= 12; month++) {
                        const isActive = month === currentMonth ? 'active' : '';
                        gridHtml += `<div class="time-item ${isActive}" data-month="${month}">${month}月</div>`;
                    }
                } else if (currentPeriod === 'year') {
                    gridClass = 'year-grid';
                    timeDisplay.text('选择年份');

                    // 生成最近几年
                    const startYear = currentYear - 2;
                    for (let year = startYear; year <= currentYear + 2; year++) {
                        const isActive = year === currentYear ? 'active' : '';
                        gridHtml += `<div class="time-item ${isActive}" data-year="${year}">${year}年</div>`;
                    }
                }

                grid.removeClass('week-grid month-grid year-grid').addClass(gridClass);
                grid.html(gridHtml);

                // 绑定点击事件
                $('.time-item').click(function() {
                    $('.time-item').removeClass('active');
                    $(this).addClass('active');

                    if (currentPeriod === 'week') {
                        currentWeek = parseInt($(this).data('week'));
                    } else if (currentPeriod === 'month') {
                        currentMonth = parseInt($(this).data('month'));
                    } else if (currentPeriod === 'year') {
                        currentYear = parseInt($(this).data('year'));
                    }

                    updatePeriodDisplay();
                    $('#time-picker').hide();
                    $('#period-display').removeClass('active');

                    // 更新URL参数
                    updateUrlParams();

                    // 重新加载数据
                    loadSummaryData();
                    loadTrendChart();
                    loadRankingData();
                });
            }

            // 时间导航 - 用于时间选择器弹窗
            function navigateTime(direction) {
                if (currentPeriod === 'week') {
                    // 周统计模式下，导航切换月份
                    currentMonth += direction;
                    if (currentMonth < 1) {
                        currentMonth = 12;
                        currentYear--;
                    } else if (currentMonth > 12) {
                        currentMonth = 1;
                        currentYear++;
                    }
                    // 重置到第一周
                    currentWeek = 1;
                } else if (currentPeriod === 'month') {
                    // 月统计模式下，导航切换年份
                    currentYear += direction;
                    // 重置到第一个月
                    currentMonth = 1;
                } else if (currentPeriod === 'year') {
                    // 年统计模式下，导航切换年份组
                    currentYear += direction * 5;
                }

                updatePeriodDisplay();
                generateTimeGrid();
                updateTimeTabs(); // 重新生成时间选择标签
                
                // 更新URL参数
                updateUrlParams();
                
                loadSummaryData();
                loadTrendChart();
                loadRankingData();
            }
            
            // 时间选择器导航按钮 - 切换大周期
            function navigatePeriod(direction) {
                if (currentPeriod === 'week') {
                    // 周统计模式下，导航切换月份
                    currentMonth += direction;
                    if (currentMonth < 1) {
                        currentMonth = 12;
                        currentYear--;
                    } else if (currentMonth > 12) {
                        currentMonth = 1;
                        currentYear++;
                    }
                    // 重置到第一周
                    currentWeek = 1;
                } else if (currentPeriod === 'month') {
                    // 月统计模式下，导航切换年份
                    currentYear += direction;
                } else if (currentPeriod === 'year') {
                    // 年统计模式下，导航切换5年一组
                    currentYear += direction * 5;
                }

                updateTimeTabs(); // 重新生成时间选择标签
                updatePeriodDisplay();
                
                // 更新URL参数
                updateUrlParams();
                
                loadSummaryData();
                loadTrendChart();
                loadRankingData();
            }

            // 加载概览数据
            function loadSummaryData() {
                const dateRange = getCurrentDateRange();
                
                if (currentStatsType === 'all') {
                    // 全部统计模式：显示收入、支出、结余
                    showAllStats();
                    
                    // 加载收入数据
                    $.ajax({
                        url: '{{ route("statistics.category") }}',
                        method: 'GET',
                        data: {
                            transaction_type: 'income',
                            start_date: dateRange.start,
                            end_date: dateRange.end
                        },
                        success: function(response) {
                            if (response.success) {
                                $('#total-income').text(formatNumber(response.data.total_amount));
                                updateBalance();
                            }
                        }
                    });
                    
                    // 加载支出数据
                    $.ajax({
                        url: '{{ route("statistics.category") }}',
                        method: 'GET',
                        data: {
                            transaction_type: 'expense',
                            start_date: dateRange.start,
                            end_date: dateRange.end
                        },
                        success: function(response) {
                            if (response.success) {
                                $('#total-expense').text(formatNumber(response.data.total_amount));
                                updateBalance();
                            }
                        }
                    });
                } else {
                    // 单项统计模式：显示总计、笔数、平均
                    showSingleStats();
                    
                    // 加载单项统计数据
                    $.ajax({
                        url: '{{ route("statistics.category") }}',
                        method: 'GET',
                        data: {
                            transaction_type: currentStatsType,
                            start_date: dateRange.start,
                            end_date: dateRange.end
                        },
                        success: function(response) {
                            if (response.success) {
                                const totalAmount = response.data.total_amount || 0;
                                // 计算总笔数：将所有分类的笔数相加
                                const totalCount = response.data.categories.reduce((sum, category) => sum + (category.count || 0), 0);
                                const averageAmount = totalCount > 0 ? totalAmount / totalCount : 0;
                                
                                $('#single-total').text(formatNumber(totalAmount));
                                $('#single-count').text(totalCount + '笔');
                                $('#single-average').text(formatNumber(averageAmount.toFixed(2)));
                                
                                // 根据统计类型设置颜色
                                const colorClass = currentStatsType === 'income' ? 'income' : 'expense';
                                $('#single-total').removeClass('income expense').addClass(colorClass);
                                $('#single-average').removeClass('income expense').addClass(colorClass);
                            }
                        }
                    });
                }
            }
            
            // 显示全部统计（收入、支出、结余）
            function showAllStats() {
                $('.all-stats').show();
                $('.single-stats').hide();
            }
            
            // 显示单项统计（总计、笔数、平均）
            function showSingleStats() {
                $('.all-stats').hide();
                $('.single-stats').show();
            }
            
            // 更新结余计算
            function updateBalance() {
                const income = parseFloat($('#total-income').text().replace('¥', '').replace(/,/g, '')) || 0;
                const expense = parseFloat($('#total-expense').text().replace('¥', '').replace(/,/g, '')) || 0;
                const balance = income - expense;
                $('#net-income').text(formatNumber(balance));

                // 设置结余颜色
                // const balanceElement = $('#net-income');
                // if (balance > 0) {
                //     balanceElement.css('color', '#10b981');
                // } else if (balance < 0) {
                //     balanceElement.css('color', '#ef4444');
                // } else {
                //     balanceElement.css('color', '#64748b');
                // }
            }

            // 获取当前日期范围
            function getCurrentDateRange() {
                let start, end;

                if (currentPeriod === 'week') {
                    // 计算周的开始和结束日期（从周一开始到周日结束）
                    const firstDay = new Date(currentYear, currentMonth - 1, 1);
                    // 找到当月第一个周一
                    const firstMonday = new Date(firstDay);
                    const dayOfWeek = firstDay.getDay(); // 0=周日, 1=周一, ..., 6=周六
                    const daysToMonday = dayOfWeek === 0 ? 1 : (8 - dayOfWeek); // 如果是周日，需要1天到周一；其他情况计算到下一个周一的天数
                    if (dayOfWeek !== 1) { // 如果第一天不是周一
                        firstMonday.setDate(firstDay.getDate() + daysToMonday);
                    }
                    
                    // 计算指定周的开始日期（周一）
                    const startOfWeek = new Date(firstMonday.getTime() + (currentWeek - 1) * 7 * 24 * 60 * 60 * 1000);
                    const endOfWeek = new Date(startOfWeek.getTime() + 6 * 24 * 60 * 60 * 1000); // 周日
                    
                    // 确保周的结束日期不超过当月最后一天
                    const lastDayOfMonth = new Date(currentYear, currentMonth, 0);
                    const actualEndOfWeek = endOfWeek > lastDayOfMonth ? lastDayOfMonth : endOfWeek;

                    // 避免时区问题，使用本地时间格式化
                    const startYear = startOfWeek.getFullYear();
                    const startMonth = String(startOfWeek.getMonth() + 1).padStart(2, '0');
                    const startDay = String(startOfWeek.getDate()).padStart(2, '0');
                    start = `${startYear}-${startMonth}-${startDay}`;
                    
                    const endYear = actualEndOfWeek.getFullYear();
                    const endMonth = String(actualEndOfWeek.getMonth() + 1).padStart(2, '0');
                    const endDay = String(actualEndOfWeek.getDate()).padStart(2, '0');
                    end = `${endYear}-${endMonth}-${endDay}`;
                } else if (currentPeriod === 'month') {
                    start = `${currentYear}-${String(currentMonth).padStart(2, '0')}-01`;
                    // 获取当月最后一天，避免时区问题
                    const lastDay = new Date(currentYear, currentMonth, 0);
                    const year = lastDay.getFullYear();
                    const month = String(lastDay.getMonth() + 1).padStart(2, '0');
                    const day = String(lastDay.getDate()).padStart(2, '0');
                    end = `${year}-${month}-${day}`;
                } else if (currentPeriod === 'year') {
                    start = `${currentYear}-01-01`;
                    end = `${currentYear}-12-31`;
                }

                return { start, end };
            }

            // 加载趋势图
            function loadTrendChart() {
                const dateRange = getCurrentDateRange();

                $.ajax({
                    url: '{{ route("statistics.trend") }}',
                    method: 'GET',
                    data: {
                        type: currentChart,
                        start_date: dateRange.start,
                        end_date: dateRange.end,
                        stats_type: currentStatsType // 添加统计类型参数
                    },
                    success: function(response) {
                        if (response.success) {
                            renderTrendChart(response.data);
                        }
                    },
                    error: function() {
                        console.error('加载趋势数据失败');
                    }
                });
            }

            // 加载排行榜数据
            function loadRankingData() {
                const dateRange = getCurrentDateRange();

                $.ajax({
                    url: '{{ route("statistics.category") }}',
                    method: 'GET',
                    data: {
                        transaction_type: currentRankingType,
                        start_date: dateRange.start,
                        end_date: dateRange.end,
                        level: currentCategoryLevel
                    },
                    success: function(response) {
                        if (response.success) {
                            renderRankingList(response.data.categories);
                            updatePieChart(response.data.categories);
                        }
                    },
                    error: function() {
                        console.error('加载排行榜数据失败');
                    }
                });
            }

            // 渲染排行榜列表
            function renderRankingList(categories) {
                const listContainer = $('#ranking-list');
                listContainer.empty();

                if (!categories || categories.length === 0) {
                    listContainer.html('<div style="text-align: center; padding: 40px; color: #64748b;">暂无数据</div>');
                    
                    return;
                }

                categories.forEach(function(item, index) {
                    const rank = index + 1;
                    let rankClass = 'other';

                    if (rank === 1) rankClass = 'top1';
                    else if (rank === 2) rankClass = 'top2';
                    else if (rank === 3) rankClass = 'top3';

                    const itemHtml = `
                        <div class="ranking-item" data-category-id="${item.category_id}" data-category="${item.category_name}" data-type="${currentRankingType}" data-level="${currentCategoryLevel}" style="cursor: pointer;">
                            <div class="ranking-rank ${rankClass}">${rank}</div>
                            <div class="ranking-info">
                                <div class="ranking-name">${item.category_name}</div>
                                <div class="ranking-percent">${item.percentage}%</div>
                            </div>
                            <div class="ranking-amount">${formatNumber(item.amount)}</div>
                        </div>
                    `;
                    listContainer.append(itemHtml);
                });
                
                // 为排行榜项添加点击事件
                $('.ranking-item').on('click', function() {
                    const categoryId = $(this).data('category-id');
                    const categoryType = $(this).data('type');
                    const categoryLevel = $(this).data('level');
                    
                    // 根据当前页面的周期类型和时间值构建URL参数
                    let periodType, periodValue;
                    
                    if (currentPeriod === 'week') {
                        periodType = 'week';
                        periodValue = `${currentYear}-${String(currentMonth).padStart(2, '0')}-${currentWeek}`;
                    } else if (currentPeriod === 'month') {
                        periodType = 'month';
                        periodValue = `${currentYear}-${String(currentMonth).padStart(2, '0')}`;
                    } else if (currentPeriod === 'year') {
                        periodType = 'year';
                        periodValue = currentYear.toString();
                    }
                    
                    // 跳转到分类详情页面
                    const url = '{{ route("statistics.category-detail") }}' + 
                                '?category_id=' + categoryId + 
                                '&type=' + categoryType + 
                                '&level=' + categoryLevel +
                                '&period_type=' + periodType + 
                                '&period_value=' + periodValue;
                    window.location.href = url;
                });
            }

            // 渲染趋势图
            function renderTrendChart(data) {
                const ctx = document.getElementById('trend-chart').getContext('2d');

                if (trendChart) {
                    trendChart.destroy();
                }
                
                // 根据统计类型决定显示的数据集
                let datasets = [];
                let allValues = [];
                
                if (currentStatsType === 'all') {
                    datasets = [{
                        data: data.income,
                        borderColor: '#10b981',
                        backgroundColor: 'transparent',
                        tension: 0,
                        fill: false,
                        pointRadius: 0,
                        pointHoverRadius: 4,
                        borderWidth: 2
                    }, {
                        data: data.expense,
                        borderColor: '#ef4444',
                        backgroundColor: 'transparent',
                        tension: 0,
                        fill: false,
                        pointRadius: 0,
                        pointHoverRadius: 4,
                        borderWidth: 2
                    }];
                    allValues = [...data.income, ...data.expense];
                } else if (currentStatsType === 'income') {
                    datasets = [{
                        data: data.income,
                        borderColor: '#10b981',
                        backgroundColor: 'transparent',
                        tension: 0,
                        fill: false,
                        pointRadius: 0,
                        pointHoverRadius: 4,
                        borderWidth: 2
                    }];
                    allValues = data.income;
                } else if (currentStatsType === 'expense') {
                    datasets = [{
                        data: data.expense,
                        borderColor: '#ef4444',
                        backgroundColor: 'transparent',
                        tension: 0,
                        fill: false,
                        pointRadius: 0,
                        pointHoverRadius: 4,
                        borderWidth: 2
                    }];
                    allValues = data.expense;
                }
                
                // 计算最高值
                const maxValue = Math.max(...allValues.filter(v => v !== null && v !== undefined));

                trendChart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: data.labels,
                        datasets: datasets
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        layout: {
                            padding: {
                                top: 20,
                                right: 10,
                                bottom: 5,
                                left: 10
                            }
                        },
                        plugins: {
                            legend: {
                                display: false
                            },
                            tooltip: {
                                callbacks: {
                                    label: function(context) {
                                        return formatNumber(context.parsed.y);
                                    }
                                }
                            }
                        },
                        scales: {
                            x: {
                                display: true,
                                grid: {
                                    display: false
                                },
                                ticks: {
                                    maxTicksLimit: 15,
                                    font: {
                                        size: 10
                                    },
                                    color: '#9ca3af'
                                },
                                border: {
                                    display: false
                                }
                            },
                            y: {
                                display: false,
                                beginAtZero: true,
                                grid: {
                                    display: false
                                },
                                border: {
                                    display: false
                                }
                            }
                        },
                        interaction: {
                            intersect: false,
                            mode: 'index'
                        },
                        elements: {
                            line: {
                                borderJoinStyle: 'round'
                            }
                        }
                    },
                    plugins: [{
                        afterDraw: function(chart) {
                            if (maxValue > 0) {
                                const ctx = chart.ctx;
                                const chartArea = chart.chartArea;
                                const yScale = chart.scales.y;
                                
                                // 绘制最高金额标注线
                                const yPosition = yScale.getPixelForValue(maxValue);
                                
                                ctx.save();
                                ctx.strokeStyle = '#d1d5db';
                                ctx.lineWidth = 1;
                                ctx.setLineDash([5, 5]);
                                ctx.beginPath();
                                ctx.moveTo(chartArea.left, yPosition);
                                ctx.lineTo(chartArea.right, yPosition);
                                ctx.stroke();
                                
                                // 绘制最高金额文字
                                ctx.fillStyle = '#6b7280';
                                ctx.font = '12px Arial';
                                ctx.textAlign = 'right';
                                ctx.fillText(formatNumber(maxValue), chartArea.right - 5, yPosition - 5);
                                ctx.restore();
                            }
                        }
                    }]
                });
            }



            // 更新饼图
            function updatePieChart(categories) {
                const ctx = document.getElementById('pie-chart').getContext('2d');
                const pieChartContainer = $('.ranking-section .chart-container');

                // 如果没有数据，隐藏饼图容器
                if (!categories || categories.length === 0) {
                    if (pieChart) {
                        pieChart.destroy();
                        pieChart = null;
                    }
                    pieChartContainer.hide();
                    return;
                }
                
                // 有数据时显示饼图容器
                pieChartContainer.show();

                // 准备饼图数据
                // 对于二级分类，去掉一级分类名前缀（仅在饼图中）
                const labels = categories.map(item => {
                    if (currentCategoryLevel === 2 && item.category_name.includes('-')) {
                        return item.category_name.split('-')[1]; // 只取二级分类名
                    }
                    return item.category_name;
                });
                const values = categories.map(item => item.amount);
                
                // 计算总金额
                const totalAmount = values.reduce((sum, value) => sum + parseFloat(value), 0);

                // 生成颜色（统一使用子分类页面的配色方案）
                const backgroundColors = [
                    'rgba(255, 99, 132, 0.7)',
                    'rgba(54, 162, 235, 0.7)',
                    'rgba(255, 206, 86, 0.7)',
                    'rgba(75, 192, 192, 0.7)',
                    'rgba(153, 102, 255, 0.7)',
                    'rgba(255, 159, 64, 0.7)',
                    'rgba(199, 199, 199, 0.7)',
                    'rgba(83, 102, 255, 0.7)',
                    'rgba(40, 159, 64, 0.7)',
                    'rgba(210, 199, 199, 0.7)'
                ];

                // 销毁旧图表
                if (pieChart) {
                    pieChart.destroy();
                }

                // 创建新图表
                pieChart = new Chart(ctx, {
                    type: 'doughnut',
                    data: {
                        labels: labels,
                        datasets: [{
                            data: values,
                            backgroundColor: backgroundColors.slice(0, categories.length),
                            borderWidth: 0,
                            hoverBorderWidth: 2,
                            hoverBorderColor: '#fff'
                        }]
                    },
                    options: {
                        responsive: true,
                        maintainAspectRatio: false,
                        plugins: {
                            legend: {
                                position: 'right',
                                align: 'center',
                                labels: {
                                    boxWidth: 12,
                                    padding: 15,
                                    font: {
                                        size: 12
                                    },
                                    usePointStyle: true,
                                    pointStyle: 'circle'
                                }
                            },
                            title: {
                                display: false
                            }
                        },
                        cutout: '50%',
                        layout: {
                            padding: {
                                left: 10,
                                right: 10,
                                top: 10,
                                bottom: 10
                            }
                        }
                    },
                    plugins: [{
                        afterDraw: function(chart) {
                            const ctx = chart.ctx;
                            const chartArea = chart.chartArea;
                            const centerX = (chartArea.left + chartArea.right) / 2;
                            const centerY = (chartArea.top + chartArea.bottom) / 2;
                            
                            ctx.save();
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            
                            // 绘制总金额
                            ctx.fillStyle = '#1e293b';
                            ctx.font = 'bold 18px Arial';
                            ctx.fillText(formatNumber(totalAmount), centerX, centerY - 8);
                            
                            // 绘制"总计"标签
                            ctx.fillStyle = '#64748b';
                            ctx.font = '12px Arial';
                            ctx.fillText('总计', centerX, centerY + 12);
                            
                            ctx.restore();
                        }
                    }]
                });
            }

            // 格式化数字（去掉￥符号和逗号分隔符）
            function formatNumber(num) {
                return parseFloat(parseFloat(num).toFixed(2)).toString();
            }

            // 增强时间标签滑动功能
            function initTimeTabsScrolling() {
                const container = document.getElementById('time-tabs-container');
                const timeTabsElement = document.getElementById('time-tabs');
                
                if (!container || !timeTabsElement) return;
                
                // 更新滑动指示器显示状态
                function updateScrollIndicators() {
                    const canScrollLeft = container.scrollLeft > 0;
                    const canScrollRight = container.scrollLeft < (container.scrollWidth - container.clientWidth);
                    
                    if (canScrollLeft) {
                        timeTabsElement.style.setProperty('--show-left-indicator', '1');
                    } else {
                        timeTabsElement.style.setProperty('--show-left-indicator', '0');
                    }
                    
                    if (canScrollRight) {
                        timeTabsElement.style.setProperty('--show-right-indicator', '1');
                    } else {
                        timeTabsElement.style.setProperty('--show-right-indicator', '0');
                    }
                }
                
                // 监听滚动事件
                container.addEventListener('scroll', updateScrollIndicators);
                
                // 初始化指示器状态
                setTimeout(updateScrollIndicators, 100);
                
                // 触摸滑动支持
                let isDown = false;
                let startX;
                let scrollLeft;
                
                container.addEventListener('mousedown', (e) => {
                    isDown = true;
                    container.style.cursor = 'grabbing';
                    startX = e.pageX - container.offsetLeft;
                    scrollLeft = container.scrollLeft;
                });
                
                container.addEventListener('mouseleave', () => {
                    isDown = false;
                    container.style.cursor = 'grab';
                });
                
                container.addEventListener('mouseup', () => {
                    isDown = false;
                    container.style.cursor = 'grab';
                });
                
                container.addEventListener('mousemove', (e) => {
                    if (!isDown) return;
                    e.preventDefault();
                    const x = e.pageX - container.offsetLeft;
                    const walk = (x - startX) * 2;
                    container.scrollLeft = scrollLeft - walk;
                });
                
                // 设置初始光标样式
                container.style.cursor = 'grab';
            }
            
            // 初始化滑动功能
            initTimeTabsScrolling();
        });
    </script>
@endpush
